<template>
  <div v-show="hideTable" class="drill-down-table task-drill-down-table">
    <div class="drill-down-table-button"> 
      <div></div>
      <div>
        <el-button v-show="isShowExportBtn && isWhiteList && allowExport" @click="exportTaskTableData(false)" type="primary">导出</el-button>
        <el-button v-show="isShowExportBtn && isWhiteList && allowExport" @click="exportTaskTableData(true)" type="primary">导出全部</el-button>
        <el-button @click="foldTable" plain>收起</el-button>
      </div>
    </div>
    
    <el-table
      :data="taskTableList"
      border
      @cell-click="getCellData"
      :header-cell-style="{'background-color': '#FAFAFA'}">

      <el-table-column v-for="(column, index) in columns" 
        :key="`${column.prop}_${index}`"
        :label="column.label"
        :prop="column.prop"
        :type="column.type"
        :min-width="column.minWidth"
        :show-overflow-tooltip="column.tooltip">

        <template slot-scope="scope">

          <template v-if="column.prop == 'synergiesName'">
            <!-- // TODO: 微信人员open-data -->
          <template v-if="isOpenData && scope.row.synergiesStaffId">
            <!-- // TODO: 微信人员open-data -->
            <open-data type="userName" :openid="scope.row.synergiesStaffId"></open-data>
          </template>
          <template v-else>
            {{ scope.row[`${column.prop}`] }}
          </template>
        </template>
        
        <template v-else-if="column.prop == 'reviewUserName'">
          <!-- // TODO: 微信人员open-data -->
          <template v-if="isOpenData && scope.row.reviewStaffId">
            <!-- // TODO: 微信人员open-data -->
            <open-data type="userName" :openid="scope.row.reviewStaffId"></open-data>
          </template>
          <template v-else>
            {{ scope.row[`${column.prop}`] }}
          </template>
        </template>

        <template v-else-if="column.prop == 'userName'">
          <span :class="{'link-text': !isExample && repeatedMaintenanceAuth}">
          <template v-if="isOpenData && scope.row.userStaffId">
            <open-data type="userName" :openid="scope.row.userStaffId"></open-data>
          </template>
          <template v-else>
            {{ scope.row[`${column.prop}`] }}
          </template>
          </span>
        </template>

        <template v-else-if="column.prop == 'customerName'">
          <span :class="{'link-text': !isExample && isAuthCustomer}">
            <template>
              {{ scope.row[`${column.prop}`] }}
            </template>
          </span>
        </template>

        <template v-else-if="column.prop == 'taskNo'">
          <span :class="{'link-text': !isExample && isAuthTask}">
            <template>
              {{ scope.row[`${column.prop}`] }}
            </template>
          </span>
        </template>

          <template v-else>
            {{ scope.row[`${column.prop}`] }}
          </template>
        </template>

      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <div class="drill-down-pagination-wrap">
      <el-pagination
        class="drill-down-pagination"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="taskTablePageParams.page"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="taskTablePageParams.pageSize"
        :layout="defaultTableData.defaultLayout"
        :total="taskTablePageParams.totalSize"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
/*  临时的 后面用工单列表组件替换 */
/* vue */
import { 
  ref,
  computed,
  watch,
  onMounted
} from 'vue'
/* model */
import { buildDegreeTaskColumns } from '@src/modules/report/managementReport/charts/components/useChartData'
import {
  getSatisfactionPineTaskData,
} from '@src/api/ManagementReport'
/* util */
import { getRootWindowInitData } from '@src/util/window';
import { isOpenData } from '@src/util/platform'
import Platform from '@src/platform'
import { 
  openTabForUserView, 
  openTabForProductView, 
  openTabForCustomerView, 
  openTabForTagHome, 
  openTabServiceProviderHome,
} from '@src/util/business/openTab'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'

/* const */
const initData = getRootWindowInitData();

// components
import BaseTableCell from 'packages/BaseTableCell';

export default {
  name: 'chart-task-table',
  props: {
    chartType: {
      type: String,
      default: ''
    },
    taskTableData: {
      type: Array,
      default: () => ([])
    },
    chartOption: {
      type: Object || String
    },
    fetchParams: {
      type: Object || String
    },
    userModuleAuth: {
      type: Object,
      default: ()=> ({})
    }
  },
  computed:{
    // 企微导出权限
    isWhiteList() {
      const { tenantType, WHITE_LIST } = initData;
      if (tenantType == 2) {
        return WHITE_LIST;
      }
      return true;
    },
    auth() {
      return initData?.user?.auth || initData?.loginUser?.authorities;
    },
    // 导出权限
    allowExport() {
      return this.auth?.REPORT_EXPORT;
    },
  },
  setup(props, { emit }) {
    const tableData = ref([])
    const taskTableList = ref([])
    const columns = ref([])
    const isOpenData = ref(isOpenData);
    // 是否开启示例
    const isExample = computed(() => {
      return props.chartOption?.isExample;
    })

    watch(tableData, () => {
      const { taskTableData, taskColumns } = buildDegreeTaskColumns(tableData.value, props.chartType, !isExample.value)
      taskTableList.value = taskTableData
      columns.value = taskColumns
    })

    const taskTablePageParams = ref({
      page: 1,
      pageSize: 10,
      totalSize: 0
    })

    const idsArray = ref([])
    const requestFunction = ref(null)

    const getData = async (ids, getDataFunction) => {
      taskTableList.value = []
      columns.value = []
      hideTable.value = true
      
      const isIds = ids ? ids : idsArray.value
      const isGetDataFunction = getDataFunction ? getDataFunction : requestFunction.value
      idsArray.value = ids
      if(getDataFunction) requestFunction.value = getDataFunction;
      if(ids !== undefined) taskTablePageParams.value.page = 1;

      let params = {
        ids: isIds,
        ...props.fetchParams,
        ...props.chartOption,
        ...taskTablePageParams.value
      }
      isGetDataFunction(params).then(res => {
        if (res.code === 200) {
          const dataReviewDTOS = res.data?.dataReviewDTOS || {}
          const list = dataReviewDTOS?.list || res.data?.list || []
          tableData.value = list || []
          taskTablePageParams.value.page = dataReviewDTOS.page || res.data.page || 1
          taskTablePageParams.value.totalSize = dataReviewDTOS.totalSize || res.data.totalSize
        } else {
          return Platform.alert(res.msg)
        }
      }).catch(error => {
        console.log(error)
      }).finally(() => {})
    }

    const handleSizeChange = value => {
      taskTablePageParams.value.pageSize = value
      getData()
    }

    const handleCurrentChange = value => {
      taskTablePageParams.value.page = value
      getData()
    }

    let hideTable = ref(true)
    const foldTable = _ => {
      hideTable.value = false
    }

    const exportTaskTableData = value => {
      const type = props.chartType === 'repeated-maintenance-rate' ? 'task' : null;
      if (value) {
        emit('export', type)
      } else {
        emit('export', type, taskTablePageParams.value)
      }
    }

    // 导出功能是否展示：表格有数据 && 不为示例数据
    const isShowExportBtn = computed(()=>{
      return taskTableList.value.length > 0 && !props.chartOption?.isExample;
    })

    // 重复维修率 产品下钻权限
    const repeatedMaintenanceAuth = computed(() => {
      if(props.chartType === 'repeated-maintenance-rate') {
        if(props.chartOption.selectType === 'PRODUCT') return isAuthProduct.value;
      }
      return true;
    })

    // 模块权限
    const isAuthTask= computed(() => {
      return props.userModuleAuth?.authTask;
    })
    const isAuthProduct = computed(() => {
      return props.userModuleAuth?.authProduct;
    })
    const isAuthCustomer = computed(() => {
      return props.userModuleAuth?.authCustomer;
    })

    // 工单跳转权限
    const isJumpTask = (id, taskNo)=>{
      if(!isAuthTask.value) return;
      openTabForTaskView(id, taskNo);
    }
    // 客户跳转权限
    const isJumpCustomer = (id)=>{
      if(!isAuthCustomer.value) return;
      openTabForCustomerView(id);
    }

    const getCellData = (row, column) => {
      // 示例数据不跳转
      if(isExample.value) return;

      // 负责人详情
      if (column.property == 'userName') {
        return row.userId && openTabForUserView(row.userId);
      }else if (column.property == 'taskNo') {
        // 工单详情
        return row.id && isJumpTask(row.id, row.taskNo);
      }else if (column.property == 'customerName') {
        // 客户详情
        return row.customerId && isJumpCustomer(row.customerId);
      }
    }

    // 跳转工单
    const openTabForTaskView = (taskId = '',taskNo = '', isNoHistory = true, isBalance = false, isAllot = false) => {
      if (!taskId) return;
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageTaskView,
        key:taskId,
        params:`${isNoHistory ? 'noHistory=1' : ''}${isBalance ? isNoHistory ? '&active=balance' : 'active=balance' : ''}${isAllot ? '&allot=true' : ''}`,
        fromId
      })
    }
 
    return {
      defaultTableData,
      hideTable,
      columns,
      taskTableList,
      taskTablePageParams,
      handleSizeChange,
      handleCurrentChange,
      foldTable,
      getData,
      exportTaskTableData,
      isShowExportBtn,
      isOpenData,
      isExample,
      getCellData,
      isAuthTask,
      isAuthProduct,
      isAuthCustomer,
      repeatedMaintenanceAuth,
    }
  },
  components: {
    [BaseTableCell.name]: BaseTableCell,
  },
};
</script>

<style lang="scss" scoped>
.drill-down-table {
  padding: 0 1%;
  margin-top: 20px;
  width: 100%;

  .drill-down-table-button {
    display: flex;
    justify-content: space-between;
  }

  .el-table {
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
    flex: 1 1 0%;
    width: 100%;
    max-width: 100%;
    margin: 16px 0;
    border-top: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    ::v-deep .el-table__empty-block {
      border-right: 1px solid #ebeef5;
      border-bottom: 1px solid #ebeef5;
    }
  }
}
</style>

<style lang="scss">
.task-drill-down-table {
  .drill-down-pagination {
    display: block !important;
    flex: 1;
    text-align: right;
    position: inherit !important;
    margin-bottom: 16px;
    .el-pagination__sizes {
      position: inherit !important;
    }
  }
}
</style>